// ContentAnalyzer.java
package com.example.netcapture.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ContentAnalyzer {

    // 在 ContentAnalyzer.java 中添加改进的文件内容提取方法
    public static String extractFileContent(String content, String contentType) {
        if (contentType.equals("http")) {
            // 只有在内容中包含 HTTP 头时才提取正文
            if (content.startsWith("HTTP/") || content.contains("GET") || content.contains("POST")) {
                return extractHttpBody(content);
            } else {
                // 否则直接返回内容（已经是正文）
                return content;
            }
        } else if (contentType.equals("base64")) {
            try {
                return new String(java.util.Base64.getDecoder().decode(content));
            } catch (Exception e) {
                return content;
            }
        }
        return content;
    }

    // 改进的HTTP body提取方法
    private static String extractHttpBody(String content) {
        if (content == null || content.isEmpty()) {
            return content;
        }

        // 查找HTTP头结束位置
        int headerEnd = content.indexOf("\r\n\r\n");
        if (headerEnd == -1) {
            headerEnd = content.indexOf("\n\n");
        }

        if (headerEnd != -1) {
            String body = content.substring(headerEnd + (content.contains("\r\n\r\n") ? 4 : 2));

            // 检查是否有Transfer-Encoding: chunked
            if (content.toLowerCase().contains("transfer-encoding: chunked")) {
                return decodeChunkedEncoding(body);
            }

            return body.trim();
        }

        return content;
    }

    // 处理分块传输编码
    private static String decodeChunkedEncoding(String chunkedBody) {
        try {
            StringBuilder result = new StringBuilder();
            String[] lines = chunkedBody.split("\r\n");
            int i = 0;

            while (i < lines.length) {
                String chunkSizeLine = lines[i].trim();
                if (chunkSizeLine.isEmpty()) {
                    i++;
                    continue;
                }

                try {
                    int chunkSize = Integer.parseInt(chunkSizeLine, 16);
                    if (chunkSize == 0) {
                        break; // 结束块
                    }

                    i++; // 移动到数据行
                    if (i < lines.length) {
                        result.append(lines[i]);
                        i++; // 移动到下一个块大小或空行
                    }
                } catch (NumberFormatException e) {
                    break;
                }
            }

            return result.toString();
        } catch (Exception e) {
            return chunkedBody;
        }
    }

    public static FileInfo analyzeContent(String content) {
        if (content == null || content.isEmpty()) {
            return new FileInfo("unknown", "unknown.bin", 0);
        }

        // 分析内容类型
        String contentType = detectContentType(content);
        String fileName = generateFileName(contentType, content);
        int fileSize = content.getBytes().length;

        return new FileInfo(contentType, fileName, fileSize);
    }

    private static String detectContentType(String content) {
        // 简单的文件类型检测逻辑
        if (content.startsWith("<?xml") || content.contains("<html>")) {
            return "text/html";
        } else if (content.startsWith("HTTP/") || content.contains("GET") || content.contains("POST")) {
            return "http";
        } else if (content.matches("^[A-Za-z0-9+/]*={0,2}$")) {
            return "base64";
        } else if (containsBinaryData(content)) {
            return "binary";
        } else {
            return "text/plain";
        }
    }

    private static String generateFileName(String contentType, String content) {
        String baseName = "exported_file";
        String extension = getFileExtension(contentType, content);

        // 尝试从HTTP头中提取文件名
        String httpFileName = extractHttpFileName(content);
        if (httpFileName != null) {
            return httpFileName;
        }

        return baseName + "." + extension;
    }

    private static String getFileExtension(String contentType, String content) {
        switch (contentType) {
            case "text/html":
                return "html";
            case "http":
                return "http";
            case "base64":
                return "b64";
            case "binary":
                return "bin";
            default:
                return "txt";
        }
    }

    private static String extractHttpFileName(String content) {
        // 尝试从Content-Disposition头中提取文件名（适用于响应）
        Pattern pattern = Pattern.compile("filename=\"([^\"]+)\"", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(content);
        if (matcher.find()) {
            return matcher.group(1);
        }

        // 改进的URL路径文件名提取（适用于请求）
        // 匹配：GET /download.html HTTP/1.1
        pattern = Pattern.compile("(?:GET|POST|PUT|DELETE|HEAD|OPTIONS)\\s+([^\\s?]+)", Pattern.CASE_INSENSITIVE);
        matcher = pattern.matcher(content);
        if (matcher.find()) {
            String path = matcher.group(1);
            // 从路径中提取文件名
            if (path.contains("/")) {
                String fileName = path.substring(path.lastIndexOf("/") + 1);
                if (!fileName.isEmpty() && fileName.contains(".")) {
                    return fileName;
                }
            } else if (path.contains(".")) {
                // 直接就是文件名的情况
                return path;
            }
        }

        return null;
    }

    private static boolean containsBinaryData(String content) {
        // 简单的二进制数据检测
        int binaryCount = 0;
        for (char c : content.toCharArray()) {
            if ((c < 32 || c > 126) && c != '\n' && c != '\r' && c != '\t') {
                binaryCount++;
            }
        }
        return binaryCount > content.length() * 0.1; // 如果超过10%是非打印字符，认为是二进制
    }

    public static class FileInfo {
        private final String contentType;
        private final String fileName;
        private final int fileSize;

        public FileInfo(String contentType, String fileName, int fileSize) {
            this.contentType = contentType;
            this.fileName = fileName;
            this.fileSize = fileSize;
        }

        public String getContentType() { return contentType; }
        public String getFileName() { return fileName; }
        public int getFileSize() { return fileSize; }
    }
}